package com.yff.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.yff.dao.IRoleDao;
import com.yff.dao.IUserDao;
import com.yff.dao.impl.RoleDaoImpl;
import com.yff.dao.impl.UserDaoImpl;
import com.yff.model.User;
import com.yff.utils.StringUtils;

/**
 * 负责完成用户信息的CRUD、登录、注销等功能
 * @author Administrator
 *
 */

@WebServlet("/user")
public class UserServlet extends HttpServlet {

	private static final long serialVersionUID = -3704200856467333570L;
	
	private IUserDao userDao=new UserDaoImpl();
	
	private IRoleDao roleDao=new RoleDaoImpl();
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("utf-8");		
		PrintWriter out=response.getWriter();
		HttpSession session = request.getSession();
		
		String type=request.getParameter("type");
		
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		
		
		Boolean flag=false;
		
		int ret=0;
		
		if(type.equals("login")) {
			login(request, response, out, username, password);
		}else if(type.equals("reg")) {
			reg(request, response, username, password);
		}else if(type.equals("logout")) {
	    	session.removeAttribute("loginInfo");
	    	session.invalidate();
	    	response.sendRedirect(request.getContextPath()+"/index");
	    }else if(type.equals("getAll")) {
	    	getAll(request, response);	    	
	    }else if(type.equals("add")) {
	    	add(request, response, username, password);
	    }else if(type.equals("get")) {
	    	get(request, response);
	    }else if(type.equals("edit")) {
	    	edit(request, response, username, password);
	    }else if(type.equals("del")) {
	    	String id=request.getParameter("id");
	    	ret=userDao.delete(Integer.parseInt(id));
			if(ret!=0) {
				response.sendRedirect(request.getContextPath()+"/user?type=getAll&page=1");
			}
	    }
	    
	}

	private void edit(HttpServletRequest request, HttpServletResponse response, String username, String password)
			throws IOException {
		int ret;
		String id=request.getParameter("id");
		User u=new User();
		u.setUsername(username);
		u.setPassword(password);
		u.setId(Integer.parseInt(id));
		u.setRoleId(2);
		ret=userDao.edit(u);
		if(ret!=0) {
			response.sendRedirect(request.getContextPath()+"/user?type=getAll&page=1");
		}
	}

	private void get(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String id=request.getParameter("id");
		User u=userDao.get(Integer.parseInt(id));
		request.setAttribute("user", u);
		RequestDispatcher dispatcher=request.getRequestDispatcher("admin/user/edituser.jsp");
		dispatcher.forward(request,response);
	}

	private void add(HttpServletRequest request, HttpServletResponse response, String username, String password)
			throws IOException {
		int ret;
		User u=new User();
		u.setUsername(username);
		u.setPassword(password);
		u.setRoleId(2);
		ret=userDao.add(u);
		if(ret!=0) {
			response.sendRedirect(request.getContextPath()+"/user?type=getAll&page=1");
		}
	}

	private void getAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String p=request.getParameter("page");
		int page;
		try {
			page=Integer.valueOf(p);
		} catch (Exception e) {
			page=1;
		}
		//每页记录数
		int pageSize=3;
		
		//某页开始记录索引
		int beginIndex=(page-1)*pageSize;
		
		List<User> userList=userDao.getAll(page,pageSize);
		for(User u:userList) {
			if(u.getRoleId()!=null) {
				u.setRoleName(roleDao.get(u.getRoleId()).getRoleName());
			}
		}
		
		String sql="select COUNT(*) from message where 1=1";
		
		Object[] params=new Object[] {};
		
		//总记录数
		int totalRecords=userDao.count(sql,params);		
		//总页数
		int totalPages=totalRecords % pageSize ==0 ? totalRecords / pageSize : totalRecords / pageSize +1;
		//某页结束的记录索引
		int endIndex=beginIndex+pageSize;  
		if(endIndex>totalRecords) {
			endIndex=totalRecords;
		}
		
		request.setAttribute("page", page);
		request.setAttribute("totalRecords", totalRecords);
		request.setAttribute("pageSize", pageSize);
		request.setAttribute("totalPages", totalPages);
		request.setAttribute("beginIndex", beginIndex);
		request.setAttribute("endIndex", endIndex);
		request.setAttribute("userList", userList);
		
		RequestDispatcher dispatcher=request.getRequestDispatcher("admin/user/users.jsp");
		dispatcher.forward(request,response);
	}

	private void reg(HttpServletRequest request, HttpServletResponse response, String username, String password)
			throws ServletException, IOException {
		int ret;
		if(StringUtils.isNotNullAndEmpty(username) && StringUtils.isNotNullAndEmpty(password)) {				
			if(userDao.isExist(username)) {
				//重名
				request.setAttribute("regInfo", "用户名已经使用，请更换！");
				RequestDispatcher dispatcher=request.getRequestDispatcher("/reg.jsp");
				dispatcher.forward(request, response);
			}else {
				//不重名
				User u=new User();
				u.setUsername(username);
				u.setPassword(password);
				u.setRoleId(2);
				ret=userDao.add(u);
				if(ret!=0) {					
					RequestDispatcher dispatcher=request.getRequestDispatcher("/login.jsp");
					dispatcher.forward(request, response);
				}else {
					request.setAttribute("regInfo", "注册失败！");
					RequestDispatcher dispatcher=request.getRequestDispatcher("/reg.jsp");
					dispatcher.forward(request, response);
				}
			}				
			
		}
	}

	private void login(HttpServletRequest request, HttpServletResponse response, PrintWriter out, String username,
			String password) throws ServletException, IOException {
		
		HttpSession session = request.getSession();		
		User u;
		if(StringUtils.isNotNullAndEmpty(username) && StringUtils.isNotNullAndEmpty(password)) {//null
			u=userDao.login(username, password);
			if(u!=null) {
				System.out.println("u========="+u);
				session.setAttribute("loginInfo", u);
				response.sendRedirect(request.getContextPath()+"/index");
			}else {
				request.setAttribute("loginInfo", "用户名或密码错误！");
				RequestDispatcher dispatcher=request.getRequestDispatcher("/login.jsp");
				dispatcher.forward(request, response);
			}
		}else {
			out.println("用户名或者密码不能为空！");
		}
	}
	
	@Override
	protected void doPost(HttpServletRequest requset, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(requset, response);
	}
	

}
